<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户注册</title>
    <style>
        body {
            font-family: "Microsoft YaHei", sans-serif;
            background: #f8f9fa;
            margin: 0;
            padding: 20px;
        }
        .container {
            max-width: 400px;
            margin: 50px auto;
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h2 {
            text-align: center;
            color: #333;
            margin-bottom: 20px;
        }
        input, select {
            width: 100%;
            padding: 10px;
            margin: 8px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            width: 100%;
            padding: 12px;
            background: #28a745;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 10px;
            transition: background 0.3s;
        }
        button:hover {
            background: #218838;
        }
        .message {
            margin-top: 15px;
            text-align: center;
            min-height: 20px; /* 防止按钮跳动 */
        }
        .error {
            color: #dc3545;
        }
        .success {
            color: #28a745;
        }
        .loading {
            color: #6c757d;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>用户注册</h2>
        <input type="text" id="username" placeholder="用户名">
        <input type="password" id="password" placeholder="密码">
        <input type="text" id="realName" placeholder="真实姓名">
        <input type="text" id="contactInfo" placeholder="联系方式">
        <input type="text" id="address" placeholder="地址（选填）">
        <select id="userRole">
            <option value="买家">买家</option>
            <option value="卖家">卖家</option>
        </select>
        <button onclick="register()">注册</button>
        <div id="message" class="message"></div>
        <p style="text-align: center; margin-top: 15px;">
            <a href="index.html">返回首页</a> | 
            <a href="login.html">已有账号？登录</a>
        </p>
    </div>
    <script>
        // 后端服务基础地址（确保与后端启动地址一致）
        const API_BASE_URL = 'http://127.0.0.1:5000';
        
        function register() {
            // 获取DOM元素
            const username = document.getElementById('username').value.trim();
            const password = document.getElementById('password').value;
            const realName = document.getElementById('realName').value.trim();
            const contactInfo = document.getElementById('contactInfo').value.trim();
            const address = document.getElementById('address').value.trim();
            const userRole = document.getElementById('userRole').value;
            const msgEl = document.getElementById('message');

            // 输入验证
            if (!username) {
                showMessage(msgEl, '请输入用户名', 'error');
                return;
            }
            if (!password) {
                showMessage(msgEl, '请输入密码', 'error');
                return;
            }
            if (password.length < 6) {
                showMessage(msgEl, '密码长度不能少于6位', 'error');
                return;
            }
            if (!realName) {
                showMessage(msgEl, '请输入真实姓名', 'error');
                return;
            }
            if (!contactInfo) {
                showMessage(msgEl, '请输入联系方式', 'error');
                return;
            }

            // 显示加载状态
            showMessage(msgEl, '注册中...', 'loading');

            // 发送注册请求
            fetch(`${API_BASE_URL}/register`, {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json'
                    // 注意：Access-Control-Allow-Credentials是后端返回的头，前端不需要设置
                },
                credentials: 'include', // 携带跨域凭证
                body: JSON.stringify({
                    username,
                    password,
                    real_name: realName,
                    contact_info: contactInfo,
                    address,
                    user_role: userRole
                })
            })
            .then(res => {
                // 处理HTTP错误状态
                if (!res.ok) {
                    if (res.status === 400) {
                        return res.json().then(data => { throw new Error(data.error || '输入信息有误') });
                    } else if (res.status === 500) {
                        throw new Error('服务器内部错误，请稍后再试');
                    } else {
                        throw new Error(`请求失败，状态码: ${res.status}`);
                    }
                }
                return res.json();
            })
            .then(data => {
                if (data.success) {
                    showMessage(msgEl, '注册成功！即将跳转到登录页...', 'success');
                    // 3秒后跳转到登录页
                    setTimeout(() => {
                        window.location.href = 'login.html';
                    }, 3000);
                } else {
                    showMessage(msgEl, data.error || '注册失败', 'error');
                }
            })
            .catch(err => {
                console.error('注册错误详情:', err);
                showMessage(msgEl, err.message, 'error');
            });
        }

        // 显示消息的工具函数
        function showMessage(element, text, type) {
            element.textContent = text;
            element.className = 'message'; // 重置样式
            element.classList.add(type);
        }

        // 监听回车键提交
        document.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                register();
            }
        });
    </script>
</body>
</html>
